package com.powernode.interception;

import com.powernode.constant.AuthConstants;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.springframework.stereotype.Component;
import org.springframework.util.ObjectUtils;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign拦截器
 */
@Component
public class FeignInterception implements RequestInterceptor {


    /**
     * 拦截器功能
     * 获取当前上下文内容
     * 获取当前请求对象
     * 将请求对象当中的token传递给 下一个请求头中
     *
     * @param requestTemplate
     */
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 通过 上下文内容 拿到请求对象
        ServletRequestAttributes requestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (!ObjectUtils.isEmpty(requestAttributes)) {
            // 获取请求对象
            HttpServletRequest request = requestAttributes.getRequest();
            // 判断是否有值
            if (!ObjectUtils.isEmpty(request)) {
                // 将当前请求头中的token值传递到下一个请求的请求头中
                requestTemplate.header(AuthConstants.AUTHORIZATION, request.getHeader(AuthConstants.AUTHORIZATION));
                return;
            }
        }
        requestTemplate.header(AuthConstants.AUTHORIZATION, AuthConstants.BEARER + "07c32215-7596-407e-a0da-d7bd2559ef1f");
    }
}
